import {Component, OnInit} from '@angular/core';
import {NzModalService, NzMessageService} from 'ng-zorro-antd';
import {UtilService} from "../../my-service/util.service";
import {TeamManagerService} from "../../my-service/teamManager.service";
import {Team} from "../Team";
import {Packet} from "../Packet";
import {Router, ActivatedRoute} from "@angular/router";

@Component({
  selector: 'start-root',
  templateUrl: './start.component.html',
  styleUrls: ['./start.component.css'],
})
export class StartComponent implements OnInit {
  readImgUrl = '';
  defaultImg ='';
  teamIndex = {
    userGuid: '',
    isOpenAddAccredit: [false],
    that: null,
    teamArr: [],//团队列表
    membersWidth: null,//团队容器所占的宽度
    onCloseAddAccredit: function (falge) {
      this.isOpenAddAccredit = falge;
    },
    addAccredit: function (type) {
      this.addAccreditType = type;
      this.isOpenAddAccredit = true;
    },
    teamList: function () {
      this.that.teamServe.getTeamList(this.userGuid).then(res => {
        if (res.status == 1) {
          res.data.forEach((team, i) => {
            this.teamArr.push(new Team(team.name, team.createTime, team.endTime, team.administrator, team.PK_teamGuid, team.status, team.adminGuid,team.limitNumber));
            this.that.isAdministrator(this.userGuid, this.teamArr[i]);//判断当前用户是不是该团队管理员
            this.that.getTeamMembers(true, this.teamArr[i]);//获得该团队所有授权用户
            this.that.getTeamMembers(false, this.teamArr[i]);//获得该团队所有未搜权的用户
            this.that.getTeamApp(this.teamArr[i]); //获得该团队所有应用
            this.that.getAllPacket(this.teamArr[i]); //获得该团队所有的教案包
          });
        } else {
          this.that.message.error('获取团队列表失败，请刷新重试');
        }
      })
    },
    countMembersWidth(clientWidth) {
      this.membersWidth = (clientWidth * 0.8 - 40) * 0.75-10;
    },
    _constructor: function () {
      this.countMembersWidth(window.document.body.clientWidth);
      this.teamList();
    }
  };

  constructor(private nzModalService: NzModalService,
              private teamServe: TeamManagerService,
              private message: NzMessageService,
              private utilServe: UtilService,
              private router: Router,
              private routerInfo: ActivatedRoute) {
    this.teamIndex.that = this;
    this.readImgUrl = this.utilServe.readImgUrl;
    this.defaultImg = this.utilServe.defaultImg;
  }

//获取用户Guid
  getUserInfo() {
    this.utilServe.getUserInfo().then(res => {
      this.teamIndex.userGuid = res.userGuid;
      this.teamIndex._constructor();
    })
  };

  // 获取团队用户信息
  getTeamUserInfo(team, type) {
    if (!type) {
      team.noAccreditMembers.forEach((member, index) => {
        this.teamServe.getUserInfo(member.FK_userGuid).then(res => {
          if (res.status == 1 && res.data) {
            team.noAccreditMembers[index] = res.data;
          } else if (res.status == 1 && !res.data) {
            team.noAccreditMembers.splice(index, 1);
            //  调用删除接口
          } else {
            console.log(res);
          }
        })
      });
    } else {
      team.haveAccreditMembers.forEach((member, index) => {
        this.teamServe.getUserInfo(member.FK_userGuid).then(res => {
          if (res.status == 1 && res.data) {
            team.haveAccreditMembers[index] = res.data;
            if (team.adminGuid == res.data.PK_UserGuid) {
              if (res.data.Cover) {
                team.Cover = res.data.Cover;
              }
            }
          } else if (res.status == 1 && !res.data) {
            team.haveAccreditMembers.splice(index, 1);
          } else {
            console.log(res);
          }
        })
      });
    }
  }

  //判断用户是否为团队管理员
  isAdministrator(userGuid, team) {
    this.teamServe.isAdministrator(team.teamGuid, userGuid).then(res => {
      if (res.status == 1) {
        team.isAdmin = res.isAdmin;
         //当管理员封面图片不存在时重新获取
        if(!team.Cover){
            this.teamServe.getUserInfo(team.adminGuid).then(res=>{
              if(res.status==1){
                team.Cover = res.data.Cover;
              }
            })
        }
      } else {
      }
    })
  }

  //获取所有团队成员Guid
  getTeamMembers(type, team) {
    this.teamServe.getTeamMembers(team.teamGuid, type).then(res => {
      if (res.status == 1) {
        if (type) {
          team.haveAccreditMembers = res.data;
          team.limitHeight(this.teamIndex.membersWidth); //计算每个团队是否需要限定高度
          this.getTeamUserInfo(team, true);
        } else {
          team.noAccreditMembers = res.data;
          this.getTeamUserInfo(team, false);
        }
      } else {
        this.message.error('获取团队成员失败');
      }
    })
  }
  /*根据团队Guid获取团队应用*/
  getTeamApp(team){
    this.teamServe.getAllApp(team.teamGuid).then(res=>{
       if(res.code==1&&res.data[0]){
          team.appArr = res.data;
       }else {
       }
    })
  }
  /*根据团队Guid获取所有的教案包(包括副本)*/
  getAllPacket(team){
    this.teamServe.getAllPacket(team.teamGuid).then(res=>{
      if(res.code==1&&res.data[0]){
        res.data.forEach((packet,index)=>{
          let packetArr = [];
          //实例化packet母本对象，并保存在数组中的0号元素
          packetArr[0] = new Packet(team.teamGuid,packet.PK_MyPacketGuid,packet.PacketName,packet.CoverUrl,packet.EnPacketName,packet.Description,packet.Publisher,packet.FK_AuthorGuid,packet.FK_CreatorGuid,packet.FK_OriginGuid);
          //有副本的情况
          if(packet.ChildrenPacket[0]){
            packet.ChildrenPacket.forEach((childrenPacket,index)=>{
              //实例化packet副本对象
              packetArr.push(new Packet(team.teamGuid,childrenPacket.PK_MyPacketGuid,childrenPacket.PacketName,childrenPacket.CoverUrl,childrenPacket.EnPacketName,childrenPacket.Description,childrenPacket.Publisher,childrenPacket.FK_AuthorGuid,childrenPacket.FK_CreatorGuid,childrenPacket.FK_OriginGuid));
            })
          }
          team.packageArr.push(packetArr);
        });
      }else {
      }
    })
  }
  ngOnInit() {
    this.getUserInfo();
    let that = this;
    window.onresize = function () {
      that.teamIndex.countMembersWidth(window.document.body.clientWidth);
      that.teamIndex.teamArr.forEach((team) => {
        team.limitHeight(that.teamIndex.membersWidth);
      })
    }
  }

  //修改团队名称
  modifyTeamName(team) {
    let data = {
      name: team.name,
      PK_teamGuid: team.teamGuid
    };
    this.teamServe.modifyTeamName(data).then(res => {
      if (res.status == 1) {
        this.message.success('修改团队名成功');
        team.isModifyTeamName = !team.isModifyTeamName;
      }
    })
  };

  /*打开团队设置*/
  openAdminSetting(team) {
    team.openAdminSeeting = true;
  }

  /*关闭团队设置*/
  closeAdminSetting(event, team) {
    team = event;
  }

  /*打开团队授权*/
  openAddAccredit(team) {
    team.openAccredit = true;
  }

  /*关闭团队授权*/
  onCloseAddAccredit(event, team) {
    team = event;
  }

  /*移除用户授权*/
  removeAccredit(team, index) {
    this.utilServe.comfirm('您确定要删除该用户的授权么？', () => {
      let data = {
        FK_teamGuid: team.teamGuid,
        FK_userGuid: team.haveAccreditMembers[index].PK_UserGuid
      };
      this.teamServe.removeAccredit(data).then(res => {
        if (res.status == 1 && res.msg == '移除授权成功') {
          this.message.success('删除用户授权成功');
          let member = team.haveAccreditMembers.splice(index, 1);
          team.noAccreditMembers.push(member[0]);
        } else {
        }
      })
    })
  }
  /*把指定用户移除团队*/
  removeMembers(team,index){
      if(team.adminGuid == team.haveAccreditMembers[index].PK_UserGuid ){
        this.message.error('当前用户为团队管理员不能将其移除团队，请更换团队管理员后将其移除');
        return;
      }
    this.utilServe.comfirm('您确定要将该用户移出团队么？', () => {
      let data = {
        FK_teamGuid: team.teamGuid,
        FK_userGuid: team.haveAccreditMembers[index].PK_UserGuid
      };
      this.teamServe.removeMembers(data).then(res => {
        if (res.status == 1 && res.msg == '移除团队成员成功') {
          this.message.success(res.msg);
          let member = team.haveAccreditMembers.splice(index, 1);
        } else {
          console.log(res);
        }
      })
    })
  }

  /*路由到详情页面*/
  gotoMinute(team) {
    this.utilServe.currentTeam = team;
    this.router.navigate(['../minute', {id: team.teamGuid, name: team.name}], {relativeTo: this.routerInfo});
  }
}

